/*
 * @Author: szx
 * @Date: 2022-03-02 14:55:05
 * @LastEditTime: 2022-03-12 13:13:18
 * @Description:
 * @FilePath: \leetcode\100-199\145\145_2.js
 */
function TreeNode(val, left, right) {
    this.val = val === undefined ? 0 : val;
    this.left = left === undefined ? null : left;
    this.right = right === undefined ? null : right;
}
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var postorderTraversal = function (root) {
    if (!root) return [];
    const st = [];
    const res = [];
    let node = root;
    let prev = null;
    while (st.length || node) {
        while (node) {
            st.push(node);
            node = node.left;
        }
        node = st.pop();
        if (node.right && prev != node.right) {
            st.push(node);
            node = node.right;
        } else {
            res.push(node.val);
            prev = node;
            node = null;
        }
    }
    return res;
};
